<template>
  <div class="chart-container">
    <div class="chart-wrapper">
      <!-- 条形图主体 -->
      <div class="bar-chart">
        <div
          v-for="(item, index) in chartData"
          :key="item.label"
          class="bar-item"
          :style="{ '--animation-delay': `${index * 100}ms` }"
          @mouseenter="hoveredIndex = index"
          @mouseleave="hoveredIndex = -1"
        >
          <!-- 条形图标签 -->
          <div class="bar-label">{{ item.label }}</div>

          <!-- 条形图本体 -->
          <div class="bar-wrapper">
            <div
              class="bar"
              :style="{
                width: hoveredIndex === index ? barWidths[index].hover : barWidths[index].base,
                backgroundColor: item.color
              }"
            ></div>
          </div>

          <!-- 条形图数值 -->
          <div class="bar-value">{{ item.value }}</div>
        </div>
      </div>
    </div>

    <!-- 控制按钮 -->
    <div class="chart-controls">
      <button
        class="refresh-btn"
        @click="fetchData"
      >
        <i class="fas fa-sync-alt"></i> 刷新数据
      </button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue';
import axios from 'axios';

// 图表数据
const chartData = ref([]);
// Bar 条比例
const kmr = ref(1);
// 当前悬停的条形图索引
const hoveredIndex = ref(-1);

function min(a, b) {
  if (a < b){
    return a;
  }
  else {
    return b;
  }
}

// 动态计算 Bar 条
const barWidths = computed(() => {
  return chartData.value.map((item, index) => {
    const baseWidth = min((item.value / kmr.value) * 100, 90); // 基础比例宽度
    const hoverWidth = min((item.value / kmr.value) * 100 + 5, 95); // 悬停时的宽度
    return {
      base: `${baseWidth}%`,
      hover: `${hoverWidth}%`
    };
  });
});

// 生成随机颜色
const getRandomColor = () => {
  const hue = Math.floor(Math.random() * 360);
  return `hsl(${hue}, 70%, 60%)`;
}

// 读取数据
async function fetchData() {
  try {
    await axios.get('http://localhost:8080/project/getTips')
      .then(response => {
        const data = response.data.msg; // 一共有多少器件

        var total = 0;
        var newData = [];
        for (let i = 0; i < min(data.length, 5); ++i) {
          newData.push({
            label: data[i].productName,
            value: data[i].num,
            color: getRandomColor()
          })
          total += data[i].num;
        }

        if (total <= 0){
          kmr.value = 1;
        }
        else {
          kmr.value = total;
        }
        chartData.value = newData;

        console.log(newData)
        console.log(kmr)
      })
      .catch(error => {
        console.error('请求出错:', error);
      });
  } catch (error) {
    console.error('async/await 请求出错:', error);
    throw error; // 可以将错误向上抛出
  }
}

fetchData();
</script>

<style scoped>
.chart-container {
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  max-width: 800px;
  margin: 2rem auto;
  padding: 0.5rem;
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.chart-title {
  color: #333;
  font-size: 1.5rem;
  margin-bottom: 1.5rem;
  text-align: center;
}

.chart-wrapper {
  padding: 1rem 0;
}

.bar-chart {
  display: flex;
  flex-direction: column;
  gap: 0; /* 原为1rem，改为0，去除bar之间的间距 */
}

.bar-item {
  display: flex;
  align-items: center;
  gap: 1rem;
  padding: 0.5rem 0;
}

.bar-label {
  width: 80px;
  font-weight: 500;
  color: #475569;
  text-align: right;
}

.bar-wrapper {
  flex: 1;
  height: 30px;
  background-color: #f1f5f9;
  border-radius: 4px;
  overflow: hidden;
  position: relative;
}

.bar {
  height: 100%;
  border-radius: 4px;
  transition: width 0.5s ease;
  animation: barGrow 1s ease-out var(--animation-delay) forwards;
  transform-origin: left center;
  transform: scaleX(0);
}

@keyframes barGrow {
  from {
    transform: scaleX(0);
  }
  to {
    transform: scaleX(1);
  }
}

.bar-value {
  width: 60px;
  font-weight: 500;
  color: #334155;
  text-align: left;
}

.chart-controls {
  display: flex;
  justify-content: left;
  margin-top: 0.5rem;
  padding: 0.5rem;
}

.refresh-btn {
  background-color: #3b82f6;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 0.5rem 1rem;
  font-weight: 500;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 0.5rem;
  transition: background-color 0.2s ease;
}

.refresh-btn:hover {
  background-color: #2563eb;
}

/* 响应式调整 */
@media (max-width: 600px) {
  .chart-container {
    padding: 1rem;
    margin: 1rem;
  }

  .bar-item {
    gap: 0.5rem;
  }

  .bar-label {
    width: 60px;
    font-size: 0.875rem;
  }

  .bar-value {
    width: 50px;
    font-size: 0.875rem;
  }
}
</style>
